package net.xujialiang.XTestRPA.Config.SpringSecurityConfig;

import com.google.gson.Gson;
import net.xujialiang.XTestRPA.Entity.XRPAUser;
import net.xujialiang.XTestRPA.Enum.LogEnum;
import net.xujialiang.XTestRPA.Service.XRPALogService;
import net.xujialiang.XTestRPA.Service.XRPAUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.io.Reader;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private XRPAUserService userService;

    @Autowired
    private XRPALogService logService;

    /***
     * 根据账号获取用户信息
     * @param username:账号
     * @param ttc:租户号
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    public UserDetails loadUserByUsername(String username, String ttc) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        XRPAUser user = userService.queryUserByNameAndTTC(username, ttc);
        if(user == null) {
            String errInfo = "用户名或密码错误!";
            try {
                logService.addLog(LogEnum.Login.getModule(), errInfo, user.getUsername(), ttc);
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            throw new UsernameNotFoundException(errInfo);
        }else{
            return new SecurityUser(user);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return null;
    }
}